<script setup lang="ts">
import { useIndicatorMethods } from '@/mixins/StatisticalIndicators/MixinIndicatorMethods'
import type { CustomDialogInstance } from '@/types/modules/public'
import type { IndicatorMethod } from '@/types/modules/statistical-indicator'

const props = defineProps<{
  type: 1 | 2
}>()
const emits = defineEmits<{
  (e: 'selected', value: IndicatorMethod): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const keyword = ref('')
const [selected, setSelected]
  = useState<IndicatorMethod | null>(null)

const { loading, columns, lists, queryIndicatorMethods }
  = useIndicatorMethods()

function open() {
  setSelected(null)
  queryIndicatorMethods(unref(keyword) ?? '', props.type)
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

function clickSearch() {
  queryIndicatorMethods(unref(keyword) ?? '', props.type)
}
function clickRow(row: IndicatorMethod) {
  close()
  setSelected(row)
}

watch(
  () => selected.value,
  (val) => {
    if (val) {
      emits('selected', val)
    }
  },
)

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="选择函数"
    :show-confirm-button="false"
    cancel-button-text="关闭"
  >
    <ElForm inline>
      <ElFormItem label="关键字">
        <ElInput
          v-model="keyword"
          clearable
          placeholder="函数/函数名称"
        />
      </ElFormItem>
      <ElFormItem>
        <SearchButton @click="clickSearch" />
      </ElFormItem>
    </ElForm>
    <div class="table-container">
      <TableLists
        :loading="loading"
        :lists="lists"
        :columns="columns"
        :show-toolbox="false"
        :no-border-bottom="true"
        :highlight-current-row="true"
        :height="360"
        style="
          --el-table-header-bg-color: var(
            --el-bg-color-page
          );
        "
        @row-click="clickRow"
      />
    </div>
  </CustomDialog>
</template>

<style scoped>
.table-container :deep(.el-table .cell) {
  white-space: pre-wrap;
}
</style>
